package com.warmlight.voicepacket;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.warmlight.voicepacket.adapter.Add2ListAdapter;
import com.warmlight.voicepacket.base.BaseActivity;
import com.warmlight.voicepacket.dao.DBFloatPlayListDetailDao;
import com.warmlight.voicepacket.data.PlaydeatalData;
import com.warmlight.voicepacket.data.RecommendFeed;
import com.warmlight.voicepacket.data.eventbus.CollectMoreAudio;
import com.warmlight.voicepacket.data.eventbus.CollectSingleAudio;
import com.warmlight.voicepacket.data.eventbus.NotifyMyPlaylist;
import com.warmlight.voicepacket.dbdata.DBFloatPlayListDetail;
import com.warmlight.voicepacket.dbdata.DBFloatPlaylist;
import com.warmlight.voicepacket.dbmanager.DBFloatPlayListDaoHelp;
import com.warmlight.voicepacket.dbmanager.DBFloatPlayListDetailDaoHelp;
import com.warmlight.voicepacket.utils.ShareCollectCallBackUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import static com.warmlight.voicepacket.db.VoicePacketDBHelper.AUDIO_ID;

/**
 * Created by jason on 2018/6/1.
 */

public class Add2ListActivity extends BaseActivity {

    //音频数据
    private RecommendFeed.DataBean.ListBean mData;
    private TextView tv_add_list;
    //本地数据库播放列表
//    private List<FloatPlayListData> mPlayListData;
    private List<DBFloatPlaylist> mPlayListData;
    private ListView lv_local_list;
    private Add2ListAdapter mAdapter;
    private ArrayList<String> mList;
    private ArrayList<PlaydeatalData.DataBean.ListBean> mType2List;
    private int addType = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add2list);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            if (bundle.containsKey("audio_id")) {
                addType = 0;
                RecommendFeed.DataBean.ListBean audioData = (RecommendFeed.DataBean.ListBean) getIntent().getSerializableExtra(AUDIO_ID);
                if (audioData != null) {
                    mData = audioData;
                }
            } else if (bundle.containsKey("my_cover")) {
                addType = 1;
                mList = (ArrayList<String>) bundle.getSerializable("my_cover");
                if (mList == null) {
                    finish();
                }
            }else if (bundle.containsKey("net_cover")){
                addType = 2;
                mType2List = (ArrayList<PlaydeatalData.DataBean.ListBean>) bundle.getSerializable("net_cover");
                if (mType2List == null) {
                    finish();
                }
            }
        }


//        mPlayListData = DBHelper.getInstance(getThis()).queryAllList();

        mPlayListData = DBFloatPlayListDaoHelp.loadAll(getThis());

        //TODO 查询本地列表并显示
//        List<FloatPlayListData> datalist = DBHelper.getInstance(getThis()).queryAllList();
//        List<DBFloatPlaylist> datalist = DBFloatPlayListDaoHelp.loadAll(getThis());

        lv_local_list = (ListView) findViewById(R.id.lv_local_list);
        mAdapter = new Add2ListAdapter(getThis(),mPlayListData);
        lv_local_list.setAdapter(mAdapter);
        lv_local_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
                if (addType == 0) {
                    //TODO 查询列表，获取列表音频字段，添加，刷新列表
                    addAudio2table(mData);
                    addAudio2List(mPlayListData.get(i).getId() + "", mData);
                }else if (addType == 1){
                    addType1ToList(mPlayListData.get(i).getId() + "",mList);

                }else if (addType == 2){
                    showProgressDialog();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {


                    ArrayList<RecommendFeed.DataBean.ListBean> list = new ArrayList<>();
                    StringBuffer stringBuffer = new StringBuffer();
                    for (int j=0;j<mType2List.size();j++){
                        PlaydeatalData.DataBean.ListBean mbean = mType2List.get(j);
                        stringBuffer.append(mbean.getId());
                        stringBuffer.append(",");

                        RecommendFeed.DataBean.ListBean bean= new RecommendFeed.DataBean.ListBean();

                        bean.setDuration(mbean.getDuration());
                        bean.setCategory_id(mbean.getCategory_id());
                        bean.setId(mbean.getId());
                        bean.setCollect(mbean.getCollect());
                        bean.setShare(mbean.getShare());
                        bean.setStar(mbean.getStar());
                        bean.setTitle(mbean.getTitle());
                        bean.setUrl(mbean.getUrl());
                        bean.setCover_pic(mbean.getPic());
                        bean.setCover_id(mbean.getCover_id());
                        bean.setCover_name(mbean.getCover_name());

                        list.add(bean);
                    }
                    DBFloatPlayListDetailDaoHelp.insert(getThis(), list);
                    addType2List(mPlayListData.get(i).getId()+"",list);
                    String s = "";
                    if (stringBuffer.length()>0){
                        s = stringBuffer.substring(0,stringBuffer.length()-1);
                    }
//                    DBFloatPlaylist data = new DBFloatPlaylist(null, "", listname, "", "1",s , "");
//                    DBFloatPlayListDaoHelp.insert(getThis(), data);
                            final String finalS = s;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    hideProgressDialog();
                                    showToast("插入成功");
                                    EventBus.getDefault().post(new NotifyMyPlaylist("notify"));
                                    EventBus.getDefault().post(new CollectMoreAudio());
                                    ShareCollectCallBackUtils.collectCallBack(finalS,"1","0");
                                    finish();
                                }
                            });
                        }
                    }).start();
                }


            }
        });

        findViewById(R.id.iv_grey).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        tv_add_list = (TextView) findViewById(R.id.tv_add_list);
        tv_add_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                DBHelper.getInstance(getThis()).addList(new FloatPlayListData("李云龙","20", TestData.mImagePath2));
//                DBHelper.getInstance(getThis()).addList(new FloatPlayListData("李云龙2","220", TestData.mImagePath3));
//                DBHelper.getInstance(getThis()).queryListDataByID("0");
                if (addType == 0) {
                    Intent intent = new Intent(getThis(), CreatePlaylistActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("AudioData", mData);
                    intent.putExtras(bundle);
                    getThis().startActivity(intent);
                }else if (addType == 1){
                    Intent intent = new Intent(getThis(), CreatePlaylistActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("audio_list",mList);
                    intent.putExtras(bundle);
                    getThis().startActivity(intent);
                }else if (addType == 2){
                    Intent intent = new Intent(getThis(), CreatePlaylistActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("net_list",mType2List);
                    intent.putExtras(bundle);
                    getThis().startActivity(intent);
                }
                finish();
            }
        });
    }

    private ProgressDialog progressDialog;
    //android.R.style.Theme_Material_Light_Dialog_Alert
    private void showProgressDialog(){
        if (progressDialog == null){
            progressDialog = new ProgressDialog(this,android.R.style.Theme_Material_Light_Dialog_Alert);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setMessage("加载数据中");
        }

        progressDialog.show();
    }

    private void hideProgressDialog(){
        if (progressDialog != null){
            if (progressDialog.isShowing()){
                progressDialog.dismiss();
            }
        }
    }

    //乱了
    private void addAudio2table(RecommendFeed.DataBean.ListBean data){
        if(data==null){
            return;
        }

//        FloatPlayListDetailData audioData = DBHelper.getInstance(getThis()).queryAudioById(data.getId());
//        DBFloatPlayListDetailDao dbFloatPlayListDetailDao = DBManager.getDaoSession(getThis()).getDBFloatPlayListDetailDao();
//        DBFloatPlayListDetail audioData = dbFloatPlayListDetailDao.queryBuilder().
//                where(DBFloatPlayListDetailDao.Properties.Audio_id.eq(data.getId())).unique();

        List<DBFloatPlayListDetail> dbFloatPlayListDetails = DBFloatPlayListDetailDaoHelp.queryBuilder(getThis(), DBFloatPlayListDetailDao.Properties.Audio_id.eq(data.getId()));

        if (dbFloatPlayListDetails != null && dbFloatPlayListDetails.size()>0){
            Log.i("WLVP","audio already existed");
            return;
        }

        List<RecommendFeed.DataBean.ListBean> list = new ArrayList<>();
        list.add(data);

        for(RecommendFeed.DataBean.ListBean data2 : list){
//            cv.put(AUDIO_ID, data.getId());
//            cv.put(AUDIO_TITLE, data.getTitle());
//            cv.put(AUDIO_URL, data.getUrl());
//            cv.put(AUDIO_COVER_ID, data.getCover_id());
//            cv.put(AUDIO_PS, data.getCover_pic());//以后扩展字段
            DBFloatPlayListDetail detail = new DBFloatPlayListDetail();
            detail.setAudio_id(data2.getId());
            detail.setAudio_title(data2.getTitle());
            detail.setAudio_url(data2.getUrl());
            detail.setAudio_cover_id(data2.getCover_id());
            detail.setAudio_ps(data2.getCover_pic());
            detail.setAudio_cover_name(data2.getCover_name());
            detail.setAudio_category_id(data2.getCategory_id());
            detail.setAudio_category_name(data2.getCategory_name());

            DBFloatPlayListDetailDaoHelp.insert(getThis(),detail);
        }
//        DBHelper.getInstance(getThis()).addAudios(list);
    }

    private void addType2List(String playlistID,ArrayList<RecommendFeed.DataBean.ListBean> audioData){
//        FloatPlayListData data = DBHelper.getInstance(getThis()).queryListDataByID(playlistID);
//        DBFloatPlaylist data = DBManager.getDaoSession(getThis()).getDBFloatPlaylistDao().queryBuilder().where(DBFloatPlaylistDao.Properties.Id.eq(playlistID))
//                .unique();
        DBFloatPlaylist data = DBFloatPlayListDaoHelp.queryBuilderById(getThis(),playlistID);
        if(data!=null){
            String[] audios = data.getList_audio().split(",");
            ArrayList<String> ids = new ArrayList<>();
            for(String id : audios){
                if (!TextUtils.isEmpty(id)) {
                    ids.add(id);
                }
            }

            for (RecommendFeed.DataBean.ListBean bean : audioData){
                if (!ids.contains(bean.getId())){
                    ids.add(0,bean.getId());
                }
            }

            StringBuffer result = new StringBuffer();
            for(String resultId : ids){
                result.append(resultId);
                result.append(",");
            }

            String newAudios = "";
            if(result!=null&&result.length()>0){
                newAudios = result.substring(0,result.length()-1);
            }

//            String audioIds = data.getList_audio();
//            if("0".equals(data.getList_count())){
                data.setList_audio(newAudios);
                data.setList_count(ids.size()+"");
//            }else{
//                //这里做一个排序，每次添加的都在最前面
//                data.setList_audio(newAudios );
//                data.setList_count(ids.size()+"");
//            }
        }

        //FIXME 此方法会修改播单的_id
//        DBHelper.getInstance(getThis()).delPlayList(playlistID);
//        DBHelper.getInstance(getThis()).addList(data);
        DBFloatPlayListDaoHelp.update(getThis(),data);

//        Toast.makeText(getThis(),"插入成功",Toast.LENGTH_SHORT).show();
//        EventBus.getDefault().post(new NotifyMyPlaylist("notify"));
////        ShareCollectCallBackUtils.collectCallBack(mData.getId(),"1");
//        finish();
    }

    //TODO 这个方法应该写在数据库里边。。。没时间
    private void addAudio2List(String playlistID,RecommendFeed.DataBean.ListBean audioData){
//        FloatPlayListData data = DBHelper.getInstance(getThis()).queryListDataByID(playlistID);
//        DBFloatPlaylist data = DBManager.getDaoSession(getThis()).getDBFloatPlaylistDao().queryBuilder().where(DBFloatPlaylistDao.Properties.Id.eq(playlistID))
//                .unique();
        DBFloatPlaylist data = DBFloatPlayListDaoHelp.queryBuilderById(getThis(),playlistID);
        if(data!=null){
            String[] audios = data.getList_audio().split(",");
            for(String id : audios){
                if(id.equals(audioData.getId())){
                    showToast("该音频存在于此播单中");
                    finish();
                    return;
                }
            }

            String audioIds = data.getList_audio();
            if("0".equals(data.getList_count())){
                data.setList_audio(audioData.getId());
                data.setList_count("1");
            }else{
                //这里做一个排序，每次添加的都在最前面
                data.setList_audio(audioData.getId() + "," + audioIds );
                data.setList_count(String.valueOf(Integer.parseInt(data.getList_count())+1));
            }
        }

        //FIXME 此方法会修改播单的_id
//        DBHelper.getInstance(getThis()).delPlayList(playlistID);
//        DBHelper.getInstance(getThis()).addList(data);
        DBFloatPlayListDaoHelp.update(getThis(),data);

        showToast("插入成功");
        EventBus.getDefault().post(new NotifyMyPlaylist("notify"));
        EventBus.getDefault().post(new CollectSingleAudio(audioData.getId()));
        ShareCollectCallBackUtils.collectCallBack(mData.getId(),"1","0");
        finish();
    }

    private void addType1ToList(final String listId, final ArrayList<String> list){
        showProgressDialog();
        new Thread(new Runnable() {
            @Override
            public void run() {


        final DBFloatPlaylist data = DBFloatPlayListDaoHelp.queryBuilderById(getThis(),listId);
        if(data!=null){
            String[] audios = data.getList_audio().split(",");

            ArrayList<String> audiolist = new ArrayList<>();
            for(String id : audios){
                if (!TextUtils.isEmpty(id)) {
                    audiolist.add(id);
                }
            }

            for (int i =0;i<list.size();i++){
                if (!audiolist.contains(list.get(i))){
                    audiolist.add(0,list.get(i));
                }else{
                }
            }

            StringBuffer result = new StringBuffer();
            for(String resultId : audiolist){
                result.append(resultId);
                result.append(",");
            }
            String s = "";
            if (result.length() > 0){
                s = result.substring(0,result.length()-1);
            }
            data.setList_audio(s);
            data.setList_count(String.valueOf(audiolist.size()));

//            String audioIds = data.getList_audio();
//            if("0".equals(data.getList_count())){
//                data.setList_audio(audioData.getId());
//                data.setList_count("1");
//            }else{
//                //这里做一个排序，每次添加的都在最前面
//                data.setList_audio(audioData.getId() + "," + audioIds );
//                data.setList_count(String.valueOf(Integer.parseInt(data.getList_count())+1));
//            }
        }

        //FIXME 此方法会修改播单的_id
//        DBHelper.getInstance(getThis()).delPlayList(playlistID);
//        DBHelper.getInstance(getThis()).addList(data);
            DBFloatPlayListDaoHelp.update(getThis(),data);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    hideProgressDialog();
                    showToast("已添加到"+data.getList_name());
                    EventBus.getDefault().post(new NotifyMyPlaylist("notify"));
    //        ShareCollectCallBackUtils.collectCallBack(mData.getId(),"1");
                    finish();
                }
            });

            }
        }).start();
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
        super.startActivityForResult(intent, requestCode, options);
        overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
    }
}
